#!/usr/bin/env node
//'use strict';

const gulp = require('gulp');
const Liftoff = require('liftoff');
const _ = require('lodash');
const path = require('path');
const moment = require('moment');
const chalk = require('chalk');
const argv = require('minimist')(process.argv.slice(2));
const fs = require('fs');
const plumber = require('gulp-plumber');
// const imagemin = require('gulp-imagemin');
const cache = require('gulp-cache');

const {fileSize} = require('./plugins/file');
const wgrep = require('./plugins/wgrep');
var config;

const timeFormat = "YYYY-MM-DD hh:mm:ss";

var webtool = new Liftoff({
    name: 'webtool', // 命令名字
    processTitle: 'webtool', //同上即可
    moduleName: 'webtool', //同上即可
    configFiles: {
        'toolconf.js': {
            cwd: '.'
        }
    },
    extensions: {
        '.js': null
    }
});

const commands = [
    {command:"init", label:"初始化,创建一个配置文件"},
    {command:"listen", label:"开始监听配置的变化"},
    {command:"build", label:"根据配置执行转换"},
    {command:"wgrep", label:"抓取指定站点内容"},
    {command:"resize", label:"重新调整图片尺雨"}
]

function ctimestr(){
    return chalk.yellow(moment().format(timeFormat));
}

//启动命令
webtool.launch({
        cwd: argv.r || argv.root, //当前输入命令的目录
        configPath: argv.f || argv.file //读取当前命令目录下的配置文件路径
    }, function(env, enc) {

        //捕获命令行
    var command = argv["_"];
    if (argv.h){
        help();
    }
    if (command.length > 0)
    {
        switch (command[0]){
            case "init":
                init(env);
                break;

            case "listen":
                listen(env);
                break;

            case "build":
                build(env);
                break;
            case "resize":
                resize(env);
                break;
            case "wgrep":
                if (command[1]){
                    wgrep(env, command[1]);
                } else {
                    console.error('wgrep 网页地址');
                }
                
                break;
            default:
        }
    }


});

function init(env){
    var configPath = path.join(process.mainModule.filename, "../../toolconf.js");
    // config = require(configPath);

    gulp.src(configPath.toLocaleString())
        .pipe(plumber())
        .pipe(gulp.dest('./'))
        .on("finish", function (){
            console.log('create config file!');
        })

}
function build(env){
    //build one , no watch
    listen(env, false);
}
function resize(env){
    var config = require(path.join(env.cwd, 'toolconf'));
    var queue = config.convert;
    _.forEach(queue, function(obj){
        if(obj.source){
            switch (obj.type.toLowerCase()){
                case "resize":
                    if (obj.sharp){
                        resizeImage(env, obj.source, obj.dest, obj.sharp);
                    }
            }
        }

    });
    
}
function listen(env, needWatch){
    var config = require(path.join(env.cwd, 'toolconf'));
    var queue = config.convert;
    needWatch = needWatch == undefined ? true : needWatch;
    _.forEach(queue, function(obj){
        if(obj.source){
            const watchTarget = obj.watch || obj.source;
            switch (obj.type.toLowerCase()){
                case "image":

                    if (obj.tinify){
                        compressImagesTinify(env, obj.source, obj.dest, obj.tinify);
                        if (needWatch)
                            gulp.watch(watchTarget, function(e){
                                logEvent(e);
                                if (e.type != 'deleted'){
                                    compressImagesTinify(env, e.path, obj.dest, obj.tinify);
                                }
                                
                            });
                    }
                    // else if (obj.imagemin){
                    //     compressImages(env, obj.source, obj.dest, imagemin);
                    //     if (needWatch)
                    //         gulp.watch(watchTarget, function(e){
                    //             logEvent(e);
                    //             if (e.type != 'deleted'){
                    //                 compressImages(env, e.path, obj.dest, imagemin);
                    //             }
                                
                    //         });
                    // }
                    break;

            }
        }

    });
}

function logEvent(e){
    switch (e.type){
        case "added":
            break;
        case "changed":
            break;

        case "deleted":
            break;
    }
    // console.log(e);
    console.log(`####${e.type} ${e.path} @${ctimestr()}####`)
}

// function compressImages(evn, source, dest, config){

//     var sourceCapacity = 0, destCapacity = 0;
//     var headMsg = `<============conver process begin @${ctimestr()}==================\n`;
//     var middMsg = '\t\t\t||\n\t\t\t||\n\t\t\t||\n\t\t\t||\n\t\t\t\\\/\n';
//     let jpgconfig = _.assign({
//         quality: 75, 
//         progressive: true
//     }, config.jpg);
//     let gifconfig = _.assign({
//         interlaced: true
//     }, config.gif);
     
//     let pngconfig = _.assign({
//         quality:[0.1, 0.2],
//     }, config.png)
//     console.log(source + "source");
//     gulp.src(source)
//         .pipe(plumber())
//         .on('data', function(file){
//             var capacity = file.contents.length;
//             sourceCapacity += file.contents.length;
//             headMsg += `${file.path}(${fileSize(capacity)})\n`
//         })
//         .pipe(imagemin([
//             // imagemin.gifsicle(gifconfig),
//             // imagemin.mozjpeg(),
//             // pngquant(pngconfig),
//             imagemin.gifsicle({interlaced: true}),
//             imagemin.mozjpeg({quality: 75, progressive: true}),
//             imagemin.optipng({optimizationLevel: 5}),
//         ], {
//             verbose:true,
//         }))
//         .pipe(gulp.dest(dest))
//         .on('data', function(file){
//             var capacity = file.contents.length;
//             destCapacity += capacity;
//             middMsg += `${file.path}(${fileSize(capacity)})\n`

//         })
//         .on('finish', function(){
//             var endMsg = `==============conver process end @${ctimestr()}================>\n`
//             // console.log(headMsg);
//             // console.log(middMsg);
//             msgConverResult(sourceCapacity, destCapacity);
//             console.log(endMsg);
//         });
// }
function resizeImage(evn, source, dest, config){
    var sourceCapacity = 0, destCapacity = 0;
    var headMsg = `<============conver process begin @${ctimestr()}==================\n`;
    var middMsg = '\t\t\t||\n\t\t\t||\n\t\t\t||\n\t\t\t||\n\t\t\t\\\/\n';
    var sharp = require('./plugins/sharp');
    gulp.src(source)
        .pipe(plumber())
        .on('data', function(file){
            var capacity = file.contents.length;
            sourceCapacity += file.contents.length;
            headMsg += `${file.path}(${fileSize(capacity)})\n`
        })
        .pipe(sharp({
            resize:config,
        }))
        .pipe(gulp.dest(dest))
        .on('data', function(file){
            // console.log(file)
            var capacity = file.contents.length;
            destCapacity += capacity;
            middMsg += `${file.path}(${fileSize(capacity)})\n`

        })
        .on('finish', function(){
            var endMsg = `==============conver process end @${ctimestr()}================>\n`
            msgConverResult(sourceCapacity, destCapacity);
            console.log(endMsg);
        });
}
function compressImagesTinify(evn, source, dest, config) {

    var sourceCapacity = 0, destCapacity = 0;
    var headMsg = `<============conver process begin @${ctimestr()}==================\n`;
    var middMsg = '\t\t\t||\n\t\t\t||\n\t\t\t||\n\t\t\t||\n\t\t\t\\\/\n';
    var {tinifycompress} = require('./plugins/tinypng');
    if (!config.apiKey)
    {
        console.log('tinify need a api to compress images');
        return;
    }
    var keys = typeof config.apiKey == "string" ? [config.apiKey] : config.apiKey;

    gulp.src(source)
        .pipe(plumber())
        .on('data', function(file){
            var capacity = file.contents.length;
            sourceCapacity += file.contents.length;
            headMsg += `${file.path}(${fileSize(capacity)})\n`
        })
        .pipe(cache(tinifycompress({
            keys:keys
        })))
        .pipe(gulp.dest(dest))
        .on('data', function(file){
            var capacity = file.contents.length;
            destCapacity += capacity;
            middMsg += `${file.path}(${fileSize(capacity)})\n`

        })
        .on('finish', function(){
            var endMsg = `==============conver process end @${ctimestr()}================>\n`
            msgConverResult(sourceCapacity, destCapacity);
            console.log(endMsg);
        });
}

function help(){
    console.log("webtool [<param>] -h");
    console.log("-h ——呼叫帮助");
    _.forEach(commands, function (obj){
        console.log(`<param>:${obj.command} -- ${obj.label}`);
    });
}
function msgConverResult(orginalSize, newSize){
    var dif = (orginalSize - newSize);
    //console.log(`${orginalSize}, ${newSize}`)
    var percent = Math.round(dif * 100 / orginalSize * 10) / 10;
    console.log(`save ${percent}% ====> ${fileSize(dif)}`);
}

//function pipeConsole(msg){
//    var stream = through(function(file, encoding,callback){
//        this.push(file);
//        callback();
//    });
//    console.log(msg);
//    return stream;
//}
